package com.gxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxh.constant.MessageConstant;
import com.gxh.constant.PasswordConstant;
import com.gxh.constant.StatusConstant;
import com.gxh.dto.EmployeeDTO;
import com.gxh.dto.EmployeeLoginDTO;
import com.gxh.dto.EmployeePageQueryDTO;
import com.gxh.entity.Employee;
import com.gxh.entity.Machine;
import com.gxh.exception.AccountLockedException;
import com.gxh.exception.AccountNotFoundException;
import com.gxh.exception.DeletionNotAllowedException;
import com.gxh.exception.PasswordErrorException;
import com.gxh.mapper.EmployeeMapper;
import com.gxh.mapper.MachineMapper;
import com.gxh.result.PageResult;
import com.gxh.service.EmployeeService;
import com.gxh.utils.AliOssUtil;
import com.gxh.vo.EmployeeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper  employeeMapper;
    @Autowired
    private MachineMapper machineMapper;
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        Employee employee = employeeMapper.selectOne(queryWrapper);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(employee.getPassword())){
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //账号锁定
        if(employee.getStatus() == StatusConstant.DISABLE){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象

        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置账号状态，默认正常
        employee.setStatus(StatusConstant.ENABLE);
        //设置密码，如果为空默认123456
        String password = employeeDTO.getPassword();
        employee.setPassword(password == null ?
                PasswordConstant.DEFAULT_PASSWORD : DigestUtils.md5DigestAsHex(password.getBytes()));
        //设置账号角色权限,默认员工
        employee.setRole("employee");
        //设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //设置当前记录的创建人和修改人
        //修改为当前登入的用户id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        //插入数据库
        employeeMapper.insertEmployee(employee);
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //select * from employee limit 0,10
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());//PageHelper可以动态地修改sql语句，实现分页查询
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> records = page.getResult();
        return new PageResult(total, records);
    }


    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    public Employee getById(Long id) {
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Employee employee = employeeMapper.selectOne(queryWrapper);
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    public void update(EmployeeDTO employeeDTO) {
        // 1. 根据 ID 查询旧的员工信息（获取旧二维码）
        Employee oldEmployee = employeeMapper.selectById(employeeDTO.getId());
        if (oldEmployee != null && StringUtils.hasText(oldEmployee.getWxQrcode())) {
            String objectName = aliOssUtil.extractObjectName(oldEmployee.getWxQrcode());
            aliOssUtil.deleteBatchOss(Arrays.asList(objectName));
        }

        // 2. 拷贝属性（包含新的二维码地址）
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        if (employeeDTO.getPassword() != null){
            employee.setPassword(DigestUtils.md5DigestAsHex(employeeDTO.getPassword().getBytes()));
        }

        // 3. 可选：设置更新时间和更新人
        // employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser(BaseContext.getCurrentId());

        // 4. 更新数据库
        employeeMapper.updateEmployee(employee);
    }


    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 批量删除员工
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        //判断员工是否禁用
        for (Long id : ids){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id",id);
            Employee employee = employeeMapper.selectOne(queryWrapper);
            if (employee.getStatus() == StatusConstant.DISABLE){
                throw new DeletionNotAllowedException(MessageConstant.ACCOUNT_LOCKED);
            }
            String objectName = aliOssUtil.extractObjectName(employee.getWxQrcode());
            aliOssUtil.deleteBatchOss(Arrays.asList(objectName));
        }

        //删除员工
        employeeMapper.deleteBatchIds(ids);
    }

    @Override
    public EmployeeVO getByMachineId(Long id) {
        Machine machine = machineMapper.selectById(id);
        if (machine != null){
            Long employeeId = machine.getCreateUser();
            Employee employee = employeeMapper.selectById(employeeId);
            EmployeeVO employeeVO = EmployeeVO.builder()
                    .id(employee.getId())
                    .name(employee.getName())
                    .phone(employee.getPhone())
                    .wxQrcode(employee.getWxQrcode())
                    .build();
            return employeeVO;
        }
        return null;
    }

}
